import { Component, OnInit, EventEmitter, HostListener } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
import { Task } from '../_common/_model/task';
import { NewTaskDto } from '../_common/_dtos/newTaskDto';
import { ListService } from '../_common/_service/list.service';
import { TaskService } from '../_common/_service/task.service';
import { List } from '../_common/_model/list';
import { RenameTitleDto } from '../_common/_dtos/renameTitleDto';
import { ContextTaskDto } from '../_common/_dtos/contextTaskDto';
import * as moment from 'moment';
import { NzModalService, NzMessageService } from 'ng-zorro-antd';
import { UpdateTaskDto } from '../_common/_dtos/updateTaskDto';

export enum KEY_CODE {
  ENTER = 13
}

export interface OptionMenu {
  show: boolean;
  type: number;
  showDoneTasks: boolean;
}

@Component({
  selector: 'app-todo',
  templateUrl: './todo.component.html',
  styleUrls: [
    './todo.component.less',
    '../_common/new-todo.less',
    '../_common/todo-list.less'
  ]
})

export class TodoComponent implements OnInit {
  tasks: Task[];
  title: string;
  newTodo: string;
  menuItems: List[];
  currentListId: string;
  currentTask: Task;
  isStaticCurrentList: boolean;
  focused = false;  // 控制添加待办事项的样式
  isTitleClicked = false; // 控制标题的样式
  isDetailDisplayed = false;  // 控制右边详情栏是否显示
  optionMenu: OptionMenu = {
    show: false,
    type: 0,
    showDoneTasks: true
  };  // 控制标题附件的选项菜单是否显示
  renameTitleEvent = new EventEmitter<any>();

  currentItem: ContextTaskDto;
  contextmenuVisible = false;
  contextmenuX = 0;
  contextmenuY = 0;

  constructor(
    private _listService: ListService,
    private _taskService: TaskService,
    private _confirm: NzModalService,
    private _message: NzMessageService,
    private _router: ActivatedRoute,
    private _Router: Router) { }

  ngOnInit(): void {
    this._router.params.subscribe(({ id }) => {
      this.currentListId = id;
      this.isDetailDisplayed = false;
      this.initWhenRouterChanged(this.currentListId);
      if (this._listService.lists) {
        this.isStaticCurrentList = this._listService.lists.find(u => u.id === id).isStatic;
      }
      // 监听url参数(newlist) 即 监听新建清单操作
      this._router.queryParams.subscribe(({ newlist }) => {
        if (Boolean(newlist)) {
          this.isTitleClicked = true;
          this.renameTitleEvent.emit(null);
        }
      });
    });
  }

  initWhenRouterChanged(id) {
    this._listService.getListTitle(id)
      .subscribe(title => this.title = title);
    this.tasks = this._listService.getTasksByListId(id);
    // 控制改变选项菜单项
    this.isStaticCurrentList =
      this._listService.lists && this._listService.lists.find(u => u.id === id).isStatic;
    if (this.tasks) {
      // 默认已完成的显示在最底下
      this.tasks.sort((a, b) => a.isDone === b.isDone ? 0 : a.isDone ? 1 : -1);
    }

    if (!this.title) {
      setTimeout(() => {
        this.initWhenRouterChanged(id);
      }, 300);
    }
  }

  clickTitle() {
    const some = this._listService.lists.some(u => u.id === this.currentListId && u.isStatic);
    if (!some) {
      this.isTitleClicked = true;
      this.renameTitleEvent.emit(null);
    }
  }

  rename() {
    this.isTitleClicked = false;
    const payload: RenameTitleDto = {
      id: this.currentListId,
      title: this.title,
      icon: 'list'
    };
    this._listService.rename(payload);
  }

  // 添加待办项目
  addNewTask() {
    if (this.newTodo && this.newTodo.trim()) {
      const newTask: NewTaskDto = {
        todo: this.newTodo.trim(),
        listId: this.currentListId
      };
      this._taskService.addNewTask(newTask)
        .subscribe(task => {
          task.index = this.tasks.length;
          this.tasks.push(task);
          const list = this._listService.lists.find(u => u.id === this.currentListId);
          list.number++;
          this.newTodo = null;
        });
    }
  }

// 监听键盘事件（添加待办项目）
  @HostListener('window: keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
    if (event.keyCode === KEY_CODE.ENTER) {
      this.addNewTask();
    }
  }
  // * 监听键盘事件
  // * https://coryrylan.com/blog/listening-to-angular-key-events-with-host-listeners
  @HostListener('window:keyup', ['$event'])
  KeyEvent(event: KeyboardEvent) {
    if (event.keyCode === KEY_CODE.ENTER) {
      this.rename();
    }
  }

  // 今日任务输入框聚焦与blur
  focus(): void {
    this.focused = true;
  }
  blur(): void {
    setTimeout(() => {
      this.focused = false;
    }, 300);
  }

  // 点击图标toggleDone
  toggleDone(task: Task, event: MouseEvent) {
    event.stopPropagation();
    const { index, isDone } = task;
    const listId = this.currentListId;
    const dto: UpdateTaskDto = {
      listId,
      index,
      ['isDone']: !isDone
    };
    this._taskService.updateTask(dto).subscribe(next => {
      const currentList = this._listService.lists.find(u => u.id === listId);
      dto.isDone ? currentList.number -- : currentList.number ++;
      currentList.tasks.find(u => u.index === index).isDone = dto.isDone;
    });
  }

  handleContextmenu(e: MouseEvent, item) {
    this.currentItem = item;
    this.currentItem.listId = this.currentListId;
    this.contextmenuVisible = true;
    this.contextmenuX = e.clientX;
    this.contextmenuY = e.clientY;
    e.preventDefault();
  }

  @HostListener('document:click') closeContextmenu() {
    this.contextmenuVisible = false;
    this.optionMenu.show = false;
    this.optionMenu.type = 0;
  }

  openDetail(task: Task) {
    this.isDetailDisplayed = true;
    this.currentItem = task;
    this.currentItem.listId = this.currentListId;
  }

  changeDetail(task: Task) {
    this.currentItem = task;
    this.currentItem.listId = this.currentListId;
  }

  onHideDetail(isHide: boolean) {
    this.isDetailDisplayed = !isHide;
  }

  renderDeadlineStyle(value: string, isDone: boolean) {
    if (isDone) { return; }
    const deadline = moment(value.substring(0, 10));
    const now = moment(moment().format('YYYY-MM-DD'));
    return deadline.diff(now) >= 0
      ? '#465efc'
      : '#fc4646';
  }

  showOptionMenu(event: MouseEvent, type: number) {
    this.optionMenu.show = true;
    this.optionMenu.type = type;
    event.stopPropagation();
  }

  toggleShowDoneTasks() {
    this.optionMenu.showDoneTasks = !this.optionMenu.showDoneTasks;
    // 该版本不开发这个功能了。
  }

  deleteList() {
    const ctx = this;
    this._confirm.confirm({
      title: '您确定要删除该清单吗？',
      content: '删除后无法恢复，请谨慎！',
      onOk: () => {
        ctx._listService.deleteList(ctx.currentListId)
          .subscribe(
          next => {
            const index = ctx._listService.lists.findIndex(u => u.id === ctx.currentListId);
            ctx._listService.lists.splice(index, 1);
            ctx._message.success('删除成功');
            setTimeout(() => {
              ctx._Router.navigate(['/my-day']);
            }, 1000);
          },
          err => {
            const { msg, code } = err;
            if (code && code === 4005) {
              ctx._message.error('清单不存在');
            } else {
              ctx._message.error(msg);
            }
          }
          );
      }
    });
  }
}
